<template>
  <div class="yuque-root">
    <div class="yuque-viewport">
      <iframe 
        v-if="embedUrl"
        :src="embedUrl"
        ref="yuqueIframe"
        class="yuque-iframe"
        frameborder="0"
        allowfullscreen
        scrolling="no"
        @load="onIframeLoad"
      />
      <div v-if="loading" class="status-loading">
        <div class="spinner"></div>
        文档加载中...
      </div>
      <div v-if="error" class="status-error">
        ⚠️ 文档加载失败，请<a @click="retry">重试</a>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getCurrentInstance } from 'vue'

const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()
const articleId = route.params.id
const sourceUrl = ref('')
const loading = ref(true)
const error = ref(false)
const yuqueIframe = ref(null)
let resizeObserver = null

// 生成优化后的嵌入链接
const embedUrl = computed(() => {
  if (!sourceUrl.value) return ''
  try {
    const url = new URL(sourceUrl.value)
    url.searchParams.set('view', 'doc_embed')
    url.searchParams.set('embedAutoResize', 'true')
    url.searchParams.set('hideFullScreen', 'true')
    url.searchParams.set('hideScrollbar', 'true')
    url.searchParams.set('widthMode', 'adaptive')
    return url.toString()
  } catch (e) {
    console.error('URL解析错误:', e)
    return ''
  }
})

// 获取文档详情
const fetchArticleDetail = async () => {
  console.log('获取文章详情...')
  try {
    loading.value = true
    error.value = false
    const response = await proxy.$axios.get(`/api/articles/${articleId}`)
    sourceUrl.value = response.data.sourceUrl + response.data.embedQuery
    if (!sourceUrl.value) throw new Error('未找到文档URL')
  } catch (err) {
    console.error('加载失败:', err)
    error.value = true
  } finally {
    loading.value = false
  }
}

// 智能布局协调器
const handleMessage = (event) => {
  if (!event.origin.includes('yuque.com')) return

  const { type, payload } = event.data
  
  switch (type) {
    case 'doc_height_change':
    case 'doc_ready':
      if (payload?.height) {
        const headerHeight = parseInt(getComputedStyle(document.documentElement)
          .getPropertyValue('--header-height')) || 0
        const safeHeight = Math.max(
          payload.height + 50,
          window.innerHeight - headerHeight
        )
        yuqueIframe.value.style.height = `${safeHeight}px`
        
        yuqueIframe.value.contentWindow.postMessage({
          type: 'container_dimensions',
          width: yuqueIframe.value.offsetWidth,
          height: safeHeight
        }, '*')
      }
      break
      
    case 'width_request':
      postDimensionUpdate()
      break
  }
}

// 发送尺寸更新
const postDimensionUpdate = () => {
  if (!yuqueIframe.value) return
  const containerWidth = yuqueIframe.value.offsetWidth
  const containerHeight = yuqueIframe.value.offsetHeight
  yuqueIframe.value.contentWindow.postMessage({
    type: 'container_dimensions',
    width: containerWidth,
    height: containerHeight
  }, '*')
}

// 响应式处理
const handleResize = () => {
  postDimensionUpdate()
  if (yuqueIframe.value?.contentWindow) {
    yuqueIframe.value.contentWindow.postMessage(
      { type: 'window_resize' },
      '*'
    )
  }
}

// iframe加载处理
const onIframeLoad = () => {
  // 动态获取header高度
  const header = document.querySelector('header')
  const headerHeight = header ? header.offsetHeight : 60
  document.documentElement.style.setProperty('--header-height', `${headerHeight}px`)

  postDimensionUpdate()
  window.addEventListener('resize', handleResize)
  window.addEventListener('message', handleMessage)
  
  if (window.ResizeObserver) {
    resizeObserver = new ResizeObserver(() => {
      postDimensionUpdate()
    })
    resizeObserver.observe(yuqueIframe.value)
  }
}

// 重试机制
const retry = () => {
  error.value = false
  fetchArticleDetail()
}

// 清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  window.removeEventListener('message', handleMessage)
  if (resizeObserver) resizeObserver.disconnect()
})

// 初始化
onMounted(() => {
  fetchArticleDetail()
  window.scrollTo(0, 0)
})
</script>

<style scoped>
/* 根容器 */
.yuque-root {
  --header-height: 100px; /* 默认header高度 */
  position: relative;
  background: #fff;
}

/* 桌面端布局 */
.yuque-root {
  padding: calc(var(--header-height) + 40px) 20px 40px !important;
  min-height: calc(100vh - var(--header-height));
}

.yuque-viewport {
  width: 100%;
  max-width: 1280px;
  margin: 0 auto;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .yuque-root {
    padding: var(--header-height) 0 0 0 !important;
    min-height: calc(100vh - var(--header-height));
    display: flex;
    flex-direction: column;
  }

  .yuque-viewport {
    flex: 1;
    max-width: 100%;
    border-radius: 0;
    box-shadow: none;
    max-height: calc(100vh - var(--header-height));
  }
}

/* 超小屏幕优化 */
@media (max-width: 480px) {
  .yuque-root {
    --header-height: 50px;
  }

  :deep(.content) {
    padding: 20px 0 !important;
    font-size: 15px;
    line-height: 1.7;
  }
}

/* 横屏优化 */
@media (max-width: 768px) and (orientation: landscape) {
  .yuque-viewport {
    max-height: calc(100vh - var(--header-height) - 30px);
  }
}

/* 安全区域适配 */
@supports (padding-top: env(safe-area-inset-top)) {
  .yuque-root {
    padding-top: calc(var(--header-height) + env(safe-area-inset-top)) !important;
    min-height: calc(100vh - var(--header-height) - env(safe-area-inset-top));
  }
}

/* iframe核心样式 */
.yuque-iframe {
  width: 100%;
  height: 100%;
  min-height: 100vh;
  border: none;
  vertical-align: top;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.yuque-iframe::-webkit-scrollbar {
  display: none;
}

/* iOS高度修复 */
@supports (-webkit-touch-callout: none) {
  .yuque-iframe {
    min-height: -webkit-fill-available;
  }
}

/* 加载状态 */
.status-loading {
  text-align: center;
  padding: 40px;
  color: #666;
}

.status-loading .spinner {
  display: inline-block;
  width: 24px;
  height: 24px;
  border: 3px solid #eee;
  border-top-color: #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-right: 12px;
  vertical-align: middle;
}

.status-error {
  text-align: center;
  padding: 40px;
  color: #f56c6c;
}

.status-error a {
  color: #409eff;
  cursor: pointer;
  text-decoration: underline;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 内容穿透样式 */
:deep(.layout-page) {
  max-width: none !important;
  margin: 0 auto !important;
  padding: 0 10% !important;
}

:deep(.content) {
  max-width: none !important;
  padding: 40px 0 !important;
}

:deep(table) {
  max-width: 100% !important;
  display: block;
  overflow-x: auto;
}

@media (max-width: 1024px) {
  :deep(.layout-page) {
    padding: 0 5% !important;
  }
}

@media (max-width: 768px) {
  :deep(.layout-page) {
    padding: 0 15px !important;
  }
}
</style>